using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;


public class HFDownLoadAssetHandle : MonoBehaviour, IHFRecycle
{
    /// <summary>
    /// 当前正在下载中的文件
    /// </summary>
    public stDownLoadFileInfo fileInfo { get; private set; }

    /// <summary>
    /// 加载完成回调
    /// </summary>
    public event Action<HFDownLoadAssetHandle> OnDownloadedCallaback;
    /// <summary>
    /// 是否下载成功
    /// </summary>
    public bool Success { get; private set; }
    /// <summary>
    /// 下载内容
    /// </summary>
    public byte[] data { get; private set; }
    //开始下载
    public void StartDownload(stDownLoadFileInfo fileInfo)
    {
        this.fileInfo = fileInfo;
        StartCoroutine(OnDownLoadAssets_UnityDownload());
    }
    /// <summary>
    /// 使用Unity 短连接下载方式
    /// </summary>
    /// <returns></returns>
    private IEnumerator OnDownLoadAssets_UnityDownload()
    {
        string uri = fileInfo.DownLoadPath;
        if (string.IsNullOrEmpty(uri))
        {
            uri= Path.Combine(fileInfo.UrlPathRoot, fileInfo.FileName).HFTransPathSeparatorCharToUnityChar().ToLower();
            uri = uri.Replace("\\", "/");
        }
        var uwr = UnityWebRequest.Get(uri);
        yield return uwr.SendWebRequest();
        if (uwr.result != UnityWebRequest.Result.Success)
        {
            Success = false;

        }
        else
        {
            data = uwr.downloadHandler.data;
            Success = true;
        }

        OnDownloadedCallaback?.Invoke(this);
        Recycle();
    }

    public void Recycle()
    {
        OnDownloadedCallaback = null; 
        transform.parent = null;
        Destroy(gameObject);
    }
}